package com.lxj.aspect;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxj.anno.Log;
import com.lxj.config.ManagerThreadPool;
import com.lxj.domain.SysLog;
import com.lxj.domain.SysUser;
import com.lxj.service.SysLogService;
import com.lxj.service.SysUserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author lxj
 * @date 2021/8/1 10:01
 * @Description:
 */
@Component
@Aspect
public class LogAspect {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysLogService sysLogService;


    /**
     * 记录日志的环绕通知
     *
     * @param joinPoint
     * @return
     */
    @Around(value = "@annotation(com.lxj.anno.Log)")
    public Object logAround(ProceedingJoinPoint joinPoint) {
        Object result = null;
        // 拿到方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 拿到方法名字
        String methodName = method.getName();
        // 拿到注解
        Log log = method.getAnnotation(Log.class);
        String operation = log.operation();
        // 参数
        Object[] args = joinPoint.getArgs();
        // 拿到ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteAddr();
        long start = System.currentTimeMillis();
        try {
            // 执行目标方法
            result = joinPoint.proceed(args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getUsername)
                .eq(SysUser::getUserId, userId)
        );
        // 异步
        ManagerThreadPool.poolExecutor.execute(() -> {
            // 插入sysLog表
            saveLog(ip, operation, methodName, time, sysUser, args);
        });
        return result;
    }

    private void saveLog(String ip, String operation, String methodName, long time, SysUser sysUser, Object[] args) {
        SysLog sysLog = SysLog.builder()
                .createDate(new Date())
                .ip(ip)
                .operation(operation)
                .method(methodName)
                .time(time)
                .username(sysUser.getUsername())
                .params(args == null ? "" : JSON.toJSONString(args))
                .build();
        sysLogService.save(sysLog);
    }
}
